var wilddogVideo = require('wilddog-video-base').wilddogVideo;
var callFactory = require('wilddog-video-call');
var remoteEl = document.getElementById('remote');
wilddogVideo.regService('call', callFactory);
var config = {
	authDomain: "wd3583616186aeiwng.wilddog.com"
};

function launchFullScreen(element) {
	if(element.requestFullScreen) {
		element.requestFullScreen();
	} else if(element.mozRequestFullScreen) {
		element.mozRequestFullScreen();
	} else if(element.webkitRequestFullScreen) {
		element.webkitRequestFullScreen();
	}
};
//launchFullScreen(remoteEl);
wilddog.initializeApp(config);
// 初始化 WilddogVideoCall 之前，要先经过身份认证。这里采用匿名登录的方式。推荐使用其他登录方式。
wilddog.auth().signInAnonymously()
	.then(function(user) {
		//认证成功后，初始化 WilddogVideoCall
		wilddogVideo.initialize({
			'appId': 'wd3583616186aeiwng',
			'token': user.getToken()
		})
		//获取 `WilddogVideoCall` 实例
		videoInstance = wilddogVideo.call();
	}).catch(function(error) {
		// Handle Errors here.
		console.log(error);
	});
//监听收到的邀请
videoInstance.on('called', function(conversation) {
	//通过回调函数获取到Conversation对象
	console.log(conversation);
})
videoInstance.on('token_error', function() {
	console.log('token不合法或过期');
})
/*
wilddogVideo.createLocalStream({
		captureVideo: true,
		captureAudio: true,
		dimension: '480p',
		maxFPS: 15
	})
	.then(function(wdStream) {
		localStream = wdStream;
		//将获取到的媒体流放到video标签上
		localStream.attach(localEl);
	})
	.catch(function(err) {
		console.error(err);
	});*/
mConversation = videoInstance.call(remoteUid, localStream, {
	'data': 'userData'
});
mConversation.on('stream_received', function(remoteStream) {
	//将远端流放入video标签中
	remoteStream.attach(remoteEl);
})
/*
//邀请其他用户加入会话
var invite = function(uid) {
	//主叫方发起邀请  获取的Conversation对象
	status = 'outgoingInvite';
	outgoingConversation = videoInstance.call(uid, localStream, {name:name});
	//监听主叫方事件
	outgoingConversation.on('response', function(callStatus) {
		switch(callStatus) {
			case 'ACCEPTED':
				console.log('您邀请的用户已经接受邀请！');
				//处理建立一对一视频通话后的事件
				conversationStarted(outgoingConversation);
				hangupEl.hidden = true;
				userDiv.hidden = false;
				break;
			case 'REJECTED':
				console.log('您邀请的用户已拒绝邀请，请重新邀请！');
				break;
			case 'BUSY':
				console.log('您邀请的用户正忙，请稍后再邀请！');
				inviteBusyEl.hidden = false;
				break;
			case 'TIMEOUT':
				console.log('您邀请的用户未处理请求，请重新邀请！');
				inviteTimeoutEl.hidden = false;
				break;
		}
	})
};*/





var localEl = document.getElementById('local');
var remoteEl = document.getElementById('remote');
var login = function() {
	//初始化野狗
	var config = {
		authDomain: 'wd3583616186aeiwng.wilddog.com',
		syncURL: "https://wd3583616186aeiwng.wilddogio.com"
	};
	wilddog.initializeApp(config);
	//WilddogVideoCall SDK 使用 syncAppId用以保存用户列表，方便获取邀请时对方uid。
	//定义quickstart使用的用户列表存储路径，userList 可以改为其他自定义路径
	usersref = wilddog.sync().ref();

	//野狗匿名登录 推荐使用非匿名登录方式
	wilddog.auth().signInAnonymously()
		.then(function(user) {
			//初始化WilddogVideoCall SDK
			wilddogVideo.initialize({
				'appId': 'wd3583616186aeiwng',
				'token': user.getToken()
			});
			//获取 WilddogVideoCall 对象
			videoInstance = wilddogVideo.call();
			//获取本地媒体流，并绑定到页面
			wilddogVideo.createLocalStream({
					captureVideo: true,
					captureAudio: true,
					dimension: '480p',
					maxFPS: 15
				})
				.then(function(wdStream) {
					localStream = wdStream;
					//将获取到的媒体流放到video标签上
					localStream.attach(localEl);
				})
				.catch(function(err) {
					console.error(err);
				});
			loginCb(user);
		})
		.then(function() {
			//监听收到的邀请
			videoInstance.on('called', onInviteCb);
			videoInstance.on('token_error', function() {
				alert('token不合法或过期，请重新登录！');
			})
		})
		.catch(function(err) {
			console.log(err);
			alert('请检查appid是否正确并开启匿名登录功能和实时视频服务！');
		});
};

//接受当前收到的邀请
var accept = function() {
	incomingConversation.accept(localStream).then(conversationStarted);
};

//拒绝当前收到的邀请
var reject = function() {
	incomingConversation.reject();
	inviteEl.hidden = true;
};

var conversationStarted = function(conversation) {
	status = 'accepted';
	currentConversation = conversation;
	//监听新参与者加入conversation事件
	currentConversation.on('stream_received', function(stream) {
		inviteEl.hidden = true;
		hangupEl.hidden = false;
		userDiv.hidden = true;
		usersref.child('users/' + currentUser.uid).remove();
		remoteStream = stream;
		remoteStream.attach(remoteEl);
	});
	//监听参与者离开conversation事件
	currentConversation.on('closed', onParticipantDisconnectedCb);

	currentConversation.on('local_stats', function(statistics) {
		console.log('local_stats', statistics);
	});
	currentConversation.on('remote_stats', function(statistics) {
		console.log('remote_stats', statistics);
	});
	currentConversation.on('error', function(error) {
		inviteEl.hidden = true;
		switch(error.code) {
			case 41004:
				console.log('建立完视频通话后，由于peerConnection建立失败导致的错误');
				console.log(error);
				break;
			case 41007:
				console.log('建立完视频通话后，由于网络或其他原因导致的异常中断');
				console.log(error);
				//hangupEl.hidden = true;
				//userDiv.hidden = false;
				remoteStream.detach(remoteEl);
				break;
		}
	});
};

//邀请其他用户加入会话
var invite = function(uid) {
	//主叫方发起邀请  获取的Conversation对象
	status = 'outgoingInvite';
	outgoingConversation = videoInstance.call(uid, localStream, 'test');
	//监听主叫方事件
	outgoingConversation.on('response', function(callStatus) {
		switch(callStatus) {
			case 'ACCEPTED':
				console.log('您邀请的用户已经接受邀请！');
				//处理建立一对一视频通话后的事件
				conversationStarted(outgoingConversation);
				hangupEl.hidden = true;
				userDiv.hidden = false;
				break;
			case 'REJECTED':
				console.log('您邀请的用户已拒绝邀请，请重新邀请！');
				break;
			case 'BUSY':
				console.log('您邀请的用户正忙，请稍后再邀请！');
				inviteBusyEl.hidden = false;
				break;
			case 'TIMEOUT':
				console.log('您邀请的用户未处理请求，请重新邀请！');
				inviteTimeoutEl.hidden = false;
				break;
		}
	})
};

//离开当前conversation
var disconnect = function() {
	if(currentConversation) {
		status = 'closed';
		remoteStream.detach(remoteEl);
		//Conversation提供了close函数用于主动离开conversation
		currentConversation.close();
		hangup.hidden = true;
		currentConversation = null;
		userDiv.hidden = false;
		usersref.child('users/' + currentUser.uid).set(true);
	}
}